<template>
	<div class="page-container">
		<h1>倒计时工具</h1>
		<div class="input-area">
			<el-input v-model="countdownTime" placeholder="请输入倒计时时间" :disabled="isCountingDown"
				style="width: 300px; margin-right: 20px;" />
			<el-select v-model="timeUnit" :disabled="isCountingDown" style="width: 5rem;">
				<el-option label="秒" value="second" />
				<el-option label="分钟" value="minute" />
				<el-option label="小时" value="hour" />
			</el-select>
		</div>
		<div class="time-area">{{ time }}</div>
		<div class="button-area">
			<el-button type="primary" @click="start" :disabled="isCountingDown">开始</el-button>
			<el-button type="primary" @click="pause" :disabled="!isCountingDown">暂停</el-button>
			<el-button type="danger" @click="reset" :disabled="!canReset">清空</el-button>
		</div>
		
	</div>
</template>

<script>
	export default {
		data() {
			return {
				countdownTime: null, // 倒计时时间
				timeUnit: 'second', // 时间单位
				startTime: null, // 开始时间
				timeRemain: 0, // 剩余时间（以毫秒为单位）
				timerId: null, // 定时器 ID
				isCountingDown: false, // 是否正在倒计时中
				audio: new Audio(require("@/assets/ding.mp3")) // 添加Audio对象
			};
		},
		computed: {
			time() {
				const date = new Date(this.timeRemain);
				let hours = date.getUTCHours();
				let minutes = date.getUTCMinutes();
				let seconds = date.getUTCSeconds();

				if (hours > 0) {
					minutes += hours * 60;
				}

				if (minutes > 0) {
					seconds += minutes * 60;
				}

				return `${seconds.toString().padStart(2, '0')}:${date
    .getUTCMilliseconds()
    .toString()
    .padStart(2, '0')}`;
			},
			canReset() {
				return this.isCountingDown || this.countdownTime !== null;
			}
		},
		methods: {
			start() {
				const milliseconds =
					this.countdownTime *
					(this.timeUnit === 'second' ?
						1000 :
						this.timeUnit === 'minute' ?
						60 * 1000 :
						60 * 60 * 1000);

				this.startTime = Date.now();
				this.timeRemain = milliseconds;
				this.timerId = setInterval(() => {
					this.timeRemain = milliseconds - (Date.now() - this.startTime);

					if (this.timeRemain <= 0) {
						this.timeRemain = 0;
						this.pause();
						this.playSound(); // 倒计时结束后播放声音提示
					}
				}, 100);

				this.isCountingDown = true;
			},
			pause() {
				clearInterval(this.timerId);
				this.isCountingDown = false;
			},
			reset() {
				clearInterval(this.timerId);
				this.countdownTime = null;
				this.timeRemain = 0;
				this.timerId = null;
				this.isCountingDown = false;
			},
			playSound() {
				this.audio.play(); // 播放声音
			}
		}
	};
</script>

<style>
	.time-area {
		font-size: 5rem;
		margin-bottom: 1.5rem;
	}

	.input-area {
		display: flex;
		align-items: center;
		margin-bottom: 1rem;
	}

	.button-area {
		margin-top: 2rem;
	}

	.el-select {
		width: 100px;
	}
</style>
